import SyntaxHighlighter from '@/components/SyntaxHighlighter'

const code1 = `
  const obj = {
    name: 'pony',
    hobby: ['爱好1', '爱好2'],
    other: {
      age: 18
    }
  }
`

const code2 = `
  function copyFn(obj, resultObj = {}) {
    if (typeof obj === 'object') {
      for (const key in obj) {
        if (typeof obj[key] === 'object') {
          resultObj[key] = Array.isArray(obj[key]) ? [] : {}
          copyFn(obj[key], resultObj[key])
        } else {
          resultObj[key] = obj[key]
        }
      }
    }

    return resultObj
  }
`

const obj = {
  name: 'pony',
  hobby: ['爱好1', '爱好2'],
  other: {
    age: 18
  }
}

const copyObj1 = obj

function copyFn(obj, resultObj = {}) {
  if (typeof obj === 'object') {
    for (const key in obj) {
      if (typeof obj[key] === 'object') {
        resultObj[key] = Array.isArray(obj[key]) ? [] : {}
        copyFn(obj[key], resultObj[key])
      } else {
        resultObj[key] = obj[key]
      }
    }
  }

  return resultObj
}

const copyObj2 = copyFn(obj)



function DeepCopy() {

  const handleChange = () => {
    obj.other.age = 19

    console.log('copyObj1', copyObj1)
    console.log('copyObj2', copyObj2)
  }

  return (
    <div>
      <p>手写一个深拷贝</p>
      <p>数据如下：</p>
      <SyntaxHighlighter children={code1} />
      <p>直接赋值，const copyObj = obj，这时候改变 obj.other.age = 19，copyObj1 的也会改变。打开控制台查看</p>
      <p>通过 copyFn 深拷贝方法赋值的，就不会跟着改变。见控制台 copyObj2</p>
      <button onClick={handleChange}>当改变 obj 的 age 时，copyObj 也会改变</button>
      <p>代码实现逻辑：</p>
      <SyntaxHighlighter children={code2} />
    </div>
  )
}

export default DeepCopy